/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.systemView;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumnModel;

import com.ruipengkj.bean.TCommodity;
import com.ruipengkj.bean.TConfig;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.base.query.PageIndex;
import com.ruipengkj.commons.base.query.PageModel;
import com.ruipengkj.commons.base.query.PageView;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.commons.util.print.BarcodePrint;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.JPanelFlowLayoutComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonGray;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.jpanel.QueryPanel;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.SystemManageBarCodeModel;
import com.ruipengkj.service.TCommodityService;
import com.ruipengkj.service.TConfigService;
import com.ruipengkj.view.base.BasePagePanel;

/**
 * 说明：
 * 条形码生成管理
 * @Author：黄盛强
 * @Date：2012-03-23
 */
public class SystemManageBarCode  extends BasePagePanel<TCommodity> implements Runnable{
	private static final long serialVersionUID = 1L;
	
	
	private JLabelJComboBoxComponent sift;//筛选条件是否有条形
	private JButton createButton;//生成
	
	private JButton addSelectButton;//全选
	private JButton oppositeButton;//反选
	private JButton printButton;//打印
	private JButton lookButton;//打印预览
	
	private JTable table;
	private JScrollPane tableJsp;
	private SystemManageBarCodeModel tableModel;
	
	private PageView<TCommodity> pageView;
	private PagingComponent pagingComponent;//翻页组件
	
	private TCommodityService tCommodityService;
	private TConfigService tConfigService;
	public SystemManageBarCode() {
		tCommodityService = BuildSpringApplication.getInstance().getTCommodityServiceImpl();
		tConfigService = BuildSpringApplication.getInstance().getTConfigServiceImpl();
		this.setLayout(new BorderLayout());
		init();
	}
	
	private void initModule() {
		tableModel = new SystemManageBarCodeModel();
		table=uiFactory.createRPJTable(tableModel, null, this, 30, JLabel.CENTER);
		tableJsp=uiFactory.createJScrollPane(table);
		
		TableColumnModel columnModel = table.getColumnModel();
		columnModel.getColumn(0).setCellEditor(table.getDefaultEditor(Boolean.class));
		columnModel.getColumn(0).setCellRenderer(table.getDefaultRenderer(JComboBox.class));
//		columnModel.getColumn(0).setCellRenderer(new DefaultTableCellRenderer());
		
		pageView = new PageView<TCommodity>();
		pagingComponent=new PagingComponent();
		pagingComponent.setPageDelegale(this);
	}
	
	private JPanel initTop() {
		QueryPanel queryPanel=new QueryPanel("条码生成",ImageFactory.loadImage(ImageFactory.FUN_7_ICON_4));
		JPanel top_panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		createButton = new RPJButtonBlue("生成");
		sift = new JLabelJComboBoxComponent("筛选条件：", new String[]{"全部", "不存在条形码", "已存在条形码"});
		top_panel.add(sift);
		top_panel.add(createButton);
		queryPanel.addPanel(top_panel);
//		queryPanel.addBoxPanel(top_panel);
		return queryPanel;
	}
	
	private JPanel initTail() {
		JPanel tail_panel =uiFactory.createGridJPanel(1, 2);
		addSelectButton = new RPJButtonBlue("全选");
		oppositeButton = new RPJButtonGray("反选");
		
		printButton = new RPJButtonWhite("打印");
		lookButton = new RPJButtonWhite("打印预览");
		JPanel jp2 = new JPanelFlowLayoutComponent(new Component[]{
				addSelectButton, oppositeButton,printButton,lookButton
		}, FlowLayout.LEFT);
		
		tail_panel.add(jp2);
		tail_panel.add(pagingComponent);
		
		return tail_panel;
	}
	
	private void init() {
		initModule();
		
		add(initTop(), BorderLayout.NORTH);
		add(tableJsp, BorderLayout.CENTER);
		add(initTail(), BorderLayout.SOUTH);
		initListener();
	}

	private void initListener() {
		sift.getBox().addActionListener(this);//筛选条件是否有条形
		createButton.addActionListener(this);//生成
		addSelectButton.addActionListener(this);//全选
		oppositeButton.addActionListener(this);//反选
		printButton.addActionListener(this);//打印
		lookButton.addActionListener(this);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == sift.getBox()) {//筛选条件是否有条形
			termQuery(1);
		} else if (e.getSource() == createButton) {//生成
			boolean[] bools = tableModel.getBools();
			List<TCommodity> tCommodityList = tableModel.getTCommodityList();
			if(tCommodityList==null||tCommodityList.size()==0){
				JOptionPane.showMessageDialog(null, "不存在商品信息！");
				return;
			}
			boolean select = false;//检查是否有选中的商品 如果没选中false 否则true
			for (int i = bools.length -1 ; i >= 0; --i) {
				if (bools[i]) {
					select = true;
					break;
				}
			}
			if (!select) {
				JOptionPane.showMessageDialog(null, "请先选择商品！");
				return;
			} else {
				
				for(int i=0;i<tCommodityList.size();i++){
					TCommodity goods=tCommodityList.get(i);
					if (bools[i]) {
						if(goods.getBarcode() != null && !goods.getBarcode().equals("")){
							if (Util.showConfirmDialog("存在已有条形码的商品被选中，确定重新生成条形码吗？") == 0) {
								break;
							} else {
								return;
							}
						}
					}
				}
				
//				开始生成选中的商品的条形码
				TCommodity tCommodity = null;
				try {//获取最大条形码的商品
					tCommodity = tCommodityService.getByMaxBarcodeService().getResultList().get(0);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				
				int maxBarcode_6 = 0;//最大条形码后面6位
				String maxBarcode = tCommodity.getBarcode();//最大条形码
				if (maxBarcode != null && !maxBarcode.equals("")) {
					if (maxBarcode.length() >= 7) 
						maxBarcode_6 = Integer.parseInt(maxBarcode.substring(1, 7));
					else 
						maxBarcode_6 = Integer.parseInt(maxBarcode);
				}
				for (int i = tCommodityList.size() - 1; i >= 0; --i) {
					if (bools[i]) {//选中的生成 
						String Barcode = "2";//条形码首位   2
						
						++maxBarcode_6;//2~7位最大值条形码++
						for (int t = 6 - String.valueOf(maxBarcode_6).length(); t > 0; --t)
							Barcode += "0";//maxBarcode_6不足6位用0填充
						Barcode += maxBarcode_6;
						
						for (int t = 0; t < 8; ++t) // 最后8位随机数
							Barcode += new Random().nextInt(10);
						
						tCommodityList.get(i).setBarcode(Barcode);
						try {//生成后保存进数据库
							tCommodityService.saveOrUpdateService(tCommodityList.get(i));
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				}
				table.updateUI();
			}
		} else if (e.getSource() == addSelectButton) {//全选
			int select = 0;
//			switch(JOptionPane.showConfirmDialog(null, "选择存在条形码的商品吗？")) {
//				case 0:
//					select = 0;//选择
//					break;
//				case 1:
//					select = 1;//不选择
//					break;
//				case 2:
//				case -1:
//					return;//取消
//			}
			boolean[] bools = tableModel.getBools();
			List<TCommodity> tCommodityList = tableModel.getTCommodityList();
			for (int i = bools.length - 1; i >= 0; --i) {
				if (select == 0) {
					bools[i] = true;
				} else {
					if (tCommodityList.get(i).getBarcode() == null || tCommodityList.get(i).getBarcode().equals(""))
						bools[i] = true;
				}
			}
			table.updateUI();
		} else if (e.getSource() == oppositeButton) {//反选
			boolean[] bools = tableModel.getBools();
			for (int i = bools.length - 1; i >= 0; --i) {
				bools[i] = !bools[i];
			}
			table.updateUI();
		} else if (e.getSource() == printButton) {//打印
			List<TCommodity> list=tableModel.getTCommodityList();
			boolean[] bools = tableModel.getBools();
			if(list==null||list.size()==0){
				JOptionPane.showMessageDialog(null, "不存在打印数据！");
				return;
			}
			
			boolean flag=false;
			for(int i=0;i<list.size();i++){
				TCommodity goods=list.get(i);
				if(goods.getBarcode()==null||goods.getBarcode().equals("")){
					if (bools[i]) {
						flag=true;
						break;
					}
				}
			}
			if(flag){
				JOptionPane.showMessageDialog(null, "存在条形码为空的数据，请先生成条形码");
				return;
			}
			
			List<TCommodity> printList = new ArrayList<TCommodity>();
			for(int i = 0; i < list.size(); ++i) {
				if (bools[i]) {
					for (int j = list.get(i).getNum(); j > 0; --j)
						printList.add(list.get(i));
				}
			}
			
			//打印
			try {
				List<TConfig> configList = tConfigService.findService(null);
				if(configList==null||configList.size()==0){
					JOptionPane.showMessageDialog(null, "打印失败，请先到系统设置配置打印机");
					return;
				}
				TConfig config=configList.get(0);
				if(config.getBarCodePrintName()==null||config.getBarCodePrintName().equals("")){
					JOptionPane.showMessageDialog(null, "打印失败，请先到系统设置配置打印机");
					return;
				}
				new BarcodePrint(printList,config.getBarCodePrintName()).start();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} else if (e.getSource() == lookButton){
			List<TCommodity> list=tableModel.getTCommodityList();
			boolean[] bools = tableModel.getBools();
			
			TCommodity commodity = null;
			for (int i = 0; i < list.size(); ++i) {
				if (bools[i]) {
					commodity = list.get(i);
					break;
				}
			}
			
			if (commodity == null) {
				JOptionPane.showMessageDialog(null, "请先选择商品！");
			}
			
			if (check(list, bools)) {
				new PrintLookCanvas(commodity).show();
			}
		}
	}
	
	private boolean check(List<TCommodity> list, boolean[] bools) {
		if (list == null || list.size() == 0) {
			JOptionPane.showMessageDialog(null, "不存在打印数据！");
			return false;
		}
		for(int i=0;i<list.size();i++){
			TCommodity goods=list.get(i);
			if(goods.getBarcode()==null||goods.getBarcode().equals("")){
				if (bools[i]) {
					JOptionPane.showMessageDialog(null, "存在条形码为空的数据，请先生成条形码");
					return false;
				}
			}
		}
		return true;
	}
	
//	条件查询
	@Override
	protected void termQuery(final int currentPage){
		int select = 0;
		switch (sift.getBox().getSelectedIndex()) {
			case 0://"全部", "不存在条形码", "已存在条形码"
				select = 0;
				break;
			case 1:
				select = 1;
				break;
			case 2:
				select = 2;
				break;
		}
		final int selectTemp=select;
		new Thread(){
			public void run(){
				tableJsp.getViewport().remove(table);
				tableJsp.getViewport().add(waitComponent);
				try {
					pageView.setCurrentPage(currentPage);
					PageModel<TCommodity> pageModel = tCommodityService.getByBarcodeNullService(pageView.getFirstResult(), pageView.getMaxResult(), selectTemp);
					pageView.setPageModel(pageModel);
					pageView.setPageIndex(PageIndex.getPageIndex(pageView.getPageCode(), pageView.getCurrentPage(), pageView.getTotalPage()));
					if(pageModel!=null){
						tableModel.setRowData(pageModel.getResultList());
						SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
								tableJsp.getViewport().remove(waitComponent);
								tableJsp.getViewport().add(table);
								pagingComponent.show();
							}
						});
					}else{
						//没有订单数据
						tableJsp.getViewport().remove(waitComponent);
						tableJsp.getViewport().add(table);
						tableModel.clear();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	@Override
	protected PageView<TCommodity> getPageView() {
		return pageView;
	}

	@Override
	public void run() {
		this.termQuery(1);
	}

	@Override
	public void clear() {
		tableModel.clear();
		sift.getBox().setSelectedIndex(0);
	}
}
